// * 单选按钮
<template>
  <label :class="['s-radio', { 's-radio-disabled': disabled }]">
    <span>
      <input
        v-if="hasGroup"
        v-model="model"
        type="radio"
        :value="label"
        :disabled="disabled"
        @change="handleChange"
      />
      <input
        v-else
        type="radio"
        v-model="currentValue"
        :value="label"
        :disabled="disabled"
        @change="handleChange"
      />
      <slot>{{ label }}</slot>
    </span>
  </label>
</template>

<script>
import Emitter from '../../mixins/emitter'
import { findComponentUpward } from '../../utils/assist'

export default {
  name: 'Radio',

  mixins: [Emitter],

  props: {
    label: {
      type: String,
      default: '',
    },
    value: {
      type: [String, Number, Boolean],
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    trueValue: {
      type: [String, Number, Boolean],
      default: true,
    },
    falseValue: {
      type: [String, Number, Boolean],
      default: false,
    },
  },

  data() {
    return {
      parent: null,
      model: '',
    }
  },

  computed: {
    hasGroup() {
      return this.parent !== null && this.parent !== undefined
    }, // 是否有radio-group

    currentValue: {
      get() {
        if (this.value === this.trueValue || this.value === this.falseValue) {
          return this.value === this.trueValue
        } else {
          throw new Error(
            `[skyui warn]: Value should be ${this.trueValue} or ${this.falseValue}`
          )
        }
      },
      set(checked) {
        this.$emit('input', checked ? this.trueValue : this.falseValue)
      },
    },
  },

  mounted() {
    const parent = findComponentUpward(this, 'RadioGroup')

    this.parent = parent
    if (parent) parent.updateModel()
  },

  methods: {
    handleChange(e) {
      const checked = e.target.value

      this.currentValue = checked

      if (this.hasGroup) {
        this.notifyRadioGroup({ type: 'change', data: checked })
      } else {
        this.notifyUser({ type: 'change', data: checked })
        this.notifyFormItem({ type: 'change', data: checked })
      }
    },

    notifyRadioGroup({ type, data }) {
      switch (type) {
        case 'change':
          this.parent.change(data)
          break
      }
    },
    notifyUser({ type, data }) {
      switch (type) {
        case 'change':
          this.$emit('on-change', data)
          break
      }
    },
    notifyFormItem({ type, data }) {
      switch (type) {
        case 'change':
          this.dispatch('FormItem', 'on-form-change', data)
          break
      }
    },
  },
}
</script>
